<template>
  <a-modal
    width="488px"
    :hide-title="true"
    v-model:visible="visible"
    ok-text="保存"
    cancel-text="重置"
    draggable
    :body-style="{ background: 'transparent' }"
    :modal-style="{ background: 'transparent' }"
    :footer="false"
    :unmountOnClose="true"
  >
    <div class="m-relative" v-if="infoData.name">
      <Phone :scale="1.2" ref="phoneRef">
        <div class="pt-50 flex flex-j-c" v-if="firstLoad">
          <van-loading type="spinner" />
        </div>
        <div v-else class="box-full flex-col">
          <div class="text-align-center line-h-40 text999 bgfff" v-if="infoData.name">
            <span>{{ infoData.name }}</span>
          </div>
          <div class="w-full flex-1 box m-relative" id="box">
            <a-image v-if="infoData.headImageSet" width="100%" :src="infoData.headImageSet"></a-image>
            <template v-if="infoData.type == 1">
              <div class="bgfff m-sticky z-index-10" style="top: -2px">
                <!-- <van-tabs v-model:active="active">
                <van-tab title="标签 1"></van-tab>
                <van-tab title="标签 2"></van-tab>
                <van-tab title="标签 3"></van-tab>
                <van-tab title="标签 4"></van-tab>
                <van-tab title="标签 4"></van-tab>
                <van-tab title="标签 4"></van-tab>
                <van-tab title="标签 4"></van-tab>
              </van-tabs> -->
                <div class="w-full flex flex-j-a flex-a-c mt-10">
                  <div class="flex cursor-pointer" @click="sortBy('actualPriceSort')">
                    <span class="text-size-12">券后价</span>
                    <div class="flex-col flex-j-c ml-2">
                      <div class="triangle" :class="listParams.actualPriceSort == 'asc' ? 'bc-theme' : 'bc999'"></div>
                      <div
                        class="triangle rotate180"
                        :class="listParams.actualPriceSort == 'desc' ? 'bc-theme' : 'bc999'"
                      ></div>
                    </div>
                  </div>
                  <div class="flex cursor-pointer" @click="sortBy('monthSalesSort')">
                    <span class="text-size-12">销量</span>
                    <div class="flex-col flex-j-c ml-2">
                      <div class="triangle" :class="listParams.monthSalesSort == 'asc' ? 'bc-theme' : 'bc999'"></div>
                      <div
                        class="triangle rotate180"
                        :class="listParams.monthSalesSort == 'desc' ? 'bc-theme' : 'bc999'"
                      ></div>
                    </div>
                  </div>
                  <div class="flex cursor-pointer" @click="sortBy('commissionSort')">
                    <span class="text-size-12">佣金</span>
                    <div class="flex-col flex-j-c ml-2">
                      <div class="triangle" :class="listParams.commissionSort == 'asc' ? 'bc-theme' : 'bc999'"></div>
                      <div
                        class="triangle rotate180"
                        :class="listParams.commissionSort == 'desc' ? 'bc-theme' : 'bc999'"
                      ></div>
                    </div>
                  </div>
                </div>
                <van-search
                  v-model="listParams.keyword"
                  shape="round"
                  placeholder="请输入搜索关键词"
                  @search="onRefresh"
                >
                </van-search>
              </div>
            </template>
            <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="getData">
              <div class="w-full box-border px-16 flex flex-wrap flex-j-b" v-if="infoData.listDisplayStyle == 1">
                <div class="w-10-c flex-col mb-10 text-size-8" v-for="(item, index) in goodsList">
                  <div class="mr-10 m-relative">
                    <a-image :src="item.picUrl" height="100" width="100" fit="scale-down"></a-image>
                    <div class="mask flex flex-a-c flex-j-a" v-if="infoData.type == 1">
                      <a-button type="primary" size="mini" shape="circle" status="warning" @click="deleteGoods(index)">
                        <template #icon>
                          <icon-delete />
                        </template>
                      </a-button>
                    </div>
                  </div>
                  <div class="text-overflow-2 text-size-10">{{ item.title }}</div>
                  <div class="flex flex-j-b flex-a-c">
                    <div
                      class="textfff bgff0012 round-2 h-12 line-h-12 px-2 text-size-8"
                      :class="parseAndCleanNumber(item.couponPrice) == 0 ? 'opacity-0' : 'opacity-1'"
                    >
                      {{ parseAndCleanNumber(item.couponPrice) }}元券
                    </div>
                    <span class="text999">{{ item.monthSales }}人买</span>
                  </div>
                  <div class="flex flex-j-b flex-a-c">
                    <div class="flex flex-col flex-a-c flex-j-c">
                      <div class="font-bold">￥{{ parseAndCleanNumber(item.actualPrice) }}</div>
                      <div class="text999">券后价</div>
                    </div>
                    <div class="flex flex-col flex-a-c flex-j-c">
                      <div class="font-bold text2a82e4">{{ parseAndCleanNumber(item.commissionRate) }}%</div>
                      <div class="text999">佣金比例</div>
                    </div>
                    <div class="flex flex-col flex-a-c flex-j-c">
                      <div class="font-bold textff0012">￥{{ parseAndCleanNumber(item.commission) }}</div>
                      <div class="text999">预估佣金</div>
                    </div>
                  </div>
                </div>
              </div>
              <div class="w-full box-border px-16" v-else>
                <div class="w-full flex h-20n mb-10" v-for="(item, index) in goodsList">
                  <div class="mr-10 m-relative">
                    <a-image :src="item.picUrl" height="80" width="80" fit="scale-down"></a-image>
                    <div class="mask flex flex-a-c flex-j-a" v-if="infoData.type == 1">
                      <a-button type="primary" size="mini" shape="circle" status="warning" @click="deleteGoods(index)">
                        <template #icon>
                          <icon-delete />
                        </template>
                      </a-button>
                    </div>
                  </div>
                  <div class="flex-1 h-full flex-col flex-j-b text-size-8">
                    <div class="text-overflow-2 text-size-10">{{ item.title }}</div>
                    <div class="flex flex-j-b flex-a-c">
                      <div
                        class="textfff bgff0012 round-2 h-12 line-h-12 px-2 text-size-8"
                        :class="parseAndCleanNumber(item.couponPrice) == 0 ? 'opacity-0' : 'opacity-10'"
                      >
                        {{ parseAndCleanNumber(item.couponPrice) }}元券
                      </div>
                      <span class="text999">{{ item.monthSales }}人买</span>
                    </div>
                    <div class="flex flex-j-b flex-a-c">
                      <div class="flex flex-col flex-a-c flex-j-c">
                        <div class="font-bold">￥{{ parseAndCleanNumber(item.actualPrice) }}</div>
                        <div class="text999">券后价</div>
                      </div>
                      <div class="flex flex-col flex-a-c flex-j-c">
                        <div class="font-bold text2a82e4">{{ parseAndCleanNumber(item.commissionRate) }}%</div>
                        <div class="text999">佣金比例</div>
                      </div>
                      <div class="flex flex-col flex-a-c flex-j-c">
                        <div class="font-bold textff0012">￥{{ parseAndCleanNumber(item.commission) }}</div>
                        <div class="text999">预估佣金</div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </van-list>
          </div>
        </div>
      </Phone>
      <div class="m-absolute operation flex-col">
        <a-button class="mb-14" status="success" shape="round" size="large" @click="visible = false">
          <template #icon>
            <icon-poweroff />
          </template>
          <template #default>关闭</template>
        </a-button>
        <a-button
          class="mb-14"
          status="success"
          shape="round"
          size="large"
          @click="resetList"
          v-if="infoData.type == 1"
        >
          <template #icon>
            <icon-reply />
          </template>
          <template #default>重置</template>
        </a-button>
        <a-button
          type="primary"
          status="success"
          shape="round"
          size="large"
          @click="saveList"
          v-if="infoData.type == 1"
        >
          <template #icon>
            <icon-save />
          </template>
          <template #default>保存</template>
        </a-button>
      </div>
    </div>
  </a-modal>
</template>

<script setup>
import { reAssign } from '@/utils/common'
import { goodsLibraryPreview, goodsLibraryDeleteGoods } from '@/apis'
const visible = ref(false)
const active = ref(0)
const phoneRef = ref()
const infoData = reactive({
  headImageSet: '',
  name: undefined,
  listDisplayStyle: 0,
  type: 2
})
const goodsList = ref([])
let goodsListCopy = null
let deleteList = []
const firstLoad = ref(true)
const loading = ref(false)
const finished = ref(false)
const listParams = reactive({
  page: 0,
  goodsLibraryId: undefined,
  actualPriceSort: undefined,
  monthSalesSort: undefined,
  commissionSort: undefined,
  keyword: undefined
})

// 获取列表设置
const getData = async () => {
  try {
    loading.value = true
    listParams.page++
    const res = await goodsLibraryPreview(listParams)
    reAssign(infoData, res.data)
    goodsList.value = goodsList.value.concat(res.data.goodsList)
    goodsListCopy = JSON.stringify(goodsList.value)
    if (firstLoad.value) firstLoad.value = false
    finished.value = res.data.goodsList.length === 0
  } finally {
    loading.value = false
  }
}

// 重新获取
const onRefresh = () => {
  goodsList.value = []
  listParams.page = 0
  getData()
}

// 打开编辑框并回显表单值
const onOpenModal = async (item) => {
  visible.value = true
  listParams.goodsLibraryId = item.goodsLibraryId
  onRefresh()
}

// 点击排序
const sortBy = (str) => {
  switch (str) {
    case 'actualPriceSort':
      listParams.monthSalesSort = undefined
      listParams.commissionSort = undefined
      if (listParams.actualPriceSort == 'desc') {
        listParams.actualPriceSort = 'asc'
      } else if (listParams.actualPriceSort == 'asc') {
        listParams.actualPriceSort = undefined
      } else {
        listParams.actualPriceSort = 'desc'
      }
      break
    case 'monthSalesSort':
      listParams.actualPriceSort = undefined
      listParams.commissionSort = undefined
      if (listParams.monthSalesSort == 'desc') {
        listParams.monthSalesSort = 'asc'
      } else if (listParams.monthSalesSort == 'asc') {
        listParams.monthSalesSort = undefined
      } else {
        listParams.monthSalesSort = 'desc'
      }
      break
    case 'commissionSort':
      listParams.monthSalesSort = undefined
      listParams.actualPriceSort = undefined
      if (listParams.commissionSort == 'desc') {
        listParams.commissionSort = 'asc'
      } else if (listParams.commissionSort == 'asc') {
        listParams.commissionSort = undefined
      } else {
        listParams.commissionSort = 'desc'
      }
      break
  }
  onRefresh()
}

// 删除
const deleteGoods = (index) => {
  deleteList.push(goodsList.value[index])
  goodsList.value.splice(index, 1)
}

// 点击重置
const resetList = () => {
  goodsList.value = JSON.parse(goodsListCopy)
  phoneRef.value?.showToast('已重置')
}

// 点击保存
const saveList = async () => {
  const apiArr = deleteList.map((item) => {
    return goodsLibraryDeleteGoods({
      goodsLibraryGoodsId: item.goodsLibraryGoodsId,
      goodsLibraryId: listParams.goodsLibraryId
    })
  })
  Promise.all(apiArr).then(() => {
    deleteList = []
    goodsListCopy = JSON.stringify(goodsList.value)
    phoneRef.value?.showToast('保存成功')
  })
}

// 数字格式化
const parseAndCleanNumber = (input) => {
  // 如果输入是数字类型，则转为字符串
  let numStr = typeof input === 'number' ? input.toString() : input
  if (numStr === undefined || numStr === null) {
    return '0'
  }
  // 如果是有效的数字字符串且含小数点
  if (numStr.includes('.')) {
    // 去掉末尾的零
    numStr = numStr.replace(/(\.\d*?)0+$/, '\$1')
    // 如果去掉零后小数点后没有数字，去掉小数点
    if (numStr.endsWith('.')) {
      numStr = numStr.slice(0, -1)
    }
  }

  return numStr
}

defineExpose({ onOpenModal })
</script>
<style lang="scss" scoped>
.box::-webkit-scrollbar {
  display: none;
}
.box {
  scrollbar-width: none; /* firefox */
  -ms-overflow-style: none; /* IE 10+ */
  overflow-x: hidden;
  overflow-y: auto;
}
.triangle {
  display: inline-block;
  width: 0;
  height: 0;
  border-style: solid;
  transform: rotate(0deg);
  border-width: 0 4px 4px 4px;
}
.bc999 {
  border-color: transparent transparent #999 transparent;
}
.bc-theme {
  border-color: transparent transparent rgb(var(--primary-6)) transparent;
}
.rotate180 {
  transform: rotate(180deg);
  margin-top: 1px;
}
.bgff0012 {
  background: #ff0012;
}
.text2a82e4 {
  color: #2a82e4;
}
.textff0012 {
  color: #ff0012;
}
.text-size-8 {
  font-size: 8px;
}
.w-10-c {
  width: calc((100% - 10px) / 2);
}
.mask {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 30px;
  background-color: rgba(0, 0, 0, 0.5); /* 半透明黑色 */
}
.operation {
  position: absolute;
  right: 0px;
  bottom: 120px;
}
</style>
